package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 表示该类是对所有控制器进行增强
 */
@ControllerAdvice
public class MyControllerAdvice {
    /**
     * 表示当前方法是用于捕捉异常的
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public String handler(Exception e, HandlerMethod method, HttpServletResponse response) {
        e.printStackTrace();
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            try {
                //添加响应头
                response.setContentType("application/json;charset=UTF-8");
                //用流的方式把异常信息给输出
                response.getWriter().println(JSON.toJSONString(new JsonResult(false, e.getMessage())));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }
        return "common/error";
    }

    @ExceptionHandler(LogicException.class)
    @ResponseBody
    public JsonResult handlerLogicException(LogicException e) {
        return new JsonResult(false, e.getMessage());
    }


}
